<template>
  <div>
    <div>
      <div class="app_card mb-2 pt-4 pb-4">
        <div class="d-flex justify-content-between search-form">
          <div class="flex-grow-1">
            <el-input class="w200px mr-3" v-model="queryForm.userName" placeholder="请输入用户名" clearable></el-input>
            <el-input class="w200px mr-3" v-model="queryForm.realName" placeholder="请输入姓名" clearable></el-input>
            <el-button type="primary" plain @click="onRefresh()">查询</el-button>
            <el-button type="info" @click="onReset()" link>重置</el-button>
          </div>
          <div class="d-flex">
            <el-button type="primary" @click="onAdd()">添加管理员</el-button>
            <!-- <el-button type="primary" plain @click="onDeleteMulti()">删除</el-button> -->
          </div>
        </div>
      </div>

      <div class="app_card pt-4  pb-5">
        <el-table v-loading="loading" element-loading-text="查询中..." stripe size="large" :data="dataOfTable"
          height="calc(100vh - 300px)">
          <!-- <el-table-column fixed type="selection" width="50" /> -->
          <el-table-column prop="Id" label="ID" align="center" width="150" />
          <el-table-column prop="UserName" label="用户名" align="center" />
          <el-table-column prop="RealName" label="姓名" align="center" />
          <el-table-column prop="IsSuper" label="是否超级管理员" align="center">
            <template #default="scope">
              <el-switch size="large" v-model="scope.row.IsSuper" inline-prompt disabled active-value="1"
                inactive-value="0" active-text="是" inactive-text="否" />
            </template>
          </el-table-column>
          <el-table-column prop="userType" label="管理员类型" align="center">
            <template #default="scope">
              <el-tag :type='scope.row.userType == 1 ? "success"
                : scope.row.userType == 2 ? "danger"
                  : scope.row.userType == 3 ? "warning"
                    : ""' disable-transitions>{{ findValue(userTypeOption, scope.row.userType) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="Mobile" label="手机号" align="center"> </el-table-column>
          <el-table-column prop="Status" label="状态" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.Status == 1 ? 'success' : 'danger'" disable-transitions>
                {{ scope.row.Status == 0 ? "禁用" : "启用" }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column fixed="right" label="操作" width="120" align="center">
            <template #default="scope">
              <el-button link type="primary" @click="onEditRow(scope.row)">编辑
              </el-button>

            </template>
          </el-table-column>
        </el-table>
        <Pagination ref="paginationRef" @handleChange="handleChange" />

      </div>

    </div>
    <edit-dialog ref="editDialogRef" @success="loadData()"></edit-dialog>
  </div>
</template>
  
<script setup>
/**
 * 管理员列表组件
 */
import { ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import { userTypeList } from '@/apis/model/UserModel';
import { findValue } from '@/utils/EsCommon';

//组件
import Pagination from '@/components/pagination/index.vue';
import SearchPanel from './SearchPanel.vue';
import EditDialog from './EditDialog.vue';


console.log('[INFO] 创建管理员列表组件');
// ======================================================
//                      变量声明
// ======================================================
const loading = ref(false);
const userTypeOption = ref(userTypeList);
// 组件引用
const paginationRef = ref(null);
const editDialogRef = ref(null);
// 表格数据
const dataOfTable = ref([]);

// 表格查询参数
const queryForm = ref({
  userName: "",
  realName: "",
})
// 表格查询参数
const queryParam = ref({
  sort: "Id",
  order: "desc",
  limit: 10,
  page: 1,
  query: ""
})
// 表格高级查询表单
const searchParam = ref({})
// 表格多选数据
const multipleSelection = ref([]);

// ======================================================
//                      点击操作
// ======================================================


// 点击新增按钮
const onAdd = () => {
  editDialogRef.value.show(0, '添加管理员');
}

// 批量编辑按钮
// const onEditMulti = () => {}

// 点击批量删除按钮
const onDeleteMulti = () => {
  let n = multipleSelection.value.length, ids = multipleSelection.value.map(v => v.Id).join();
  ElMessageBox.confirm(`确定要删除 ${n} 条记录吗？`, '警告').then(() => {
    EsAjax.post(ApiUrls.backenduserDelete, { param: { ids } }).then(res => {
      if (res.data.code != 200) {
        ElMessage.warning(res.data.data + res.data.msg);
        return;
      }
      ElMessage.success('删除成功');
      loadData();
    }).catch(err => {
      ElMessage.error('网络错误：' + err.message);
    })
  }).catch(() => { })
}

// 点击快速搜索按钮
const onReset = () => {
  queryForm.value.userName = ""
  queryForm.value.realName = ""
  onRefresh()
}

const onRefresh = () => {
  queryParam.value.page = 1;
  paginationRef.value?.changeTotal({ totalCount: 0 })
  loadData();
}
// 点击行内编辑按钮
const onEditRow = (row) => {
  editDialogRef.value.show(row.Id, '编辑管理员', row);
}

// ======================================================
//                      处理事件
// ======================================================

// 处理表格全选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 处理表格排序
const handleSortChange = (column) => {
  queryParam.value.orderby = column.prop + ' ' + (column.order == 'descending' ? 'desc' : 'asc');
  console.log(queryParam.value);
  loadData();
}

// 处理分页尺寸
const handleChange = (data = null) => {
  queryParam.value.page = data?.page;
  queryParam.value.limit = data?.limit;
  loadData();
}


// ======================================================
//                      处理事件
// ======================================================

const loadData = () => {
  let _queryParam = queryParam.value
  _queryParam.query = ''
  let queryList = []
  if (queryForm.value.userName) {
    queryList.push(`userName:${queryForm.value.userName}`)
  }
  if (queryForm.value.realName) {
    queryList.push(`realName:${queryForm.value.realName}`)
  }
  if (queryList.length) {
    _queryParam.query = queryList.join(',')
  }
  console.log(_queryParam.query)
  _queryParam.offset = (_queryParam.page - 1) * _queryParam.limit || 0;
  loading.value = true

  EsAjax.post(ApiUrls.backenduserDatagrid, { ..._queryParam }).then(res => {
    if (res.data.code != 200) {
      ElMessage.warning(res.data.data + res.data.msg);
      return;
    }
    let { list, totalCount } = res.data.data
    dataOfTable.value = list;
    paginationRef.value?.changeTotal({ totalCount: totalCount })
  }).catch(err => {
    ElMessage.error(err.message);
  }).finally(() => {
    loading.value = false
  })
}

loadData();
</script>
  
